package com.app.service.utils;

import com.app.model.main.*;
import com.app.model.solr.SolrFlag;
import com.app.model.util.ArticleFlag;
import com.app.model.util.CommonFlag;
import com.app.repository.interfaces.*;
import com.app.service.SolrService;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.apache.solr.common.SolrDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Lichaojie on 2017/5/4. It's a beautiful day.
 */
@Service
public class RecommendUtil {
    private final Logger logger = Logger.getLogger(RecommendUtil.class);

    @Autowired
    private LoginRecordMapper loginRecordMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private SolrService solrService;
    @Autowired
    private CommentsOfArticleMapper commentsOfArticleMapper;
    @Autowired
    private ApprovalMapper approvalMapper;
    @Autowired
    private ScanRecordMapper scanRecordMapper;
    @Autowired
    private FavoriteMapper favoriteMapper;


    /**
     * 获取某用户的时效性分数
     * @param userId 用户ID
     * @param nowTime 当前时间戳
     * @return
     */
    public double getTimeLiness(long userId,long nowTime){
        ////logger.info("getTimeLiness");
        List<LoginRecord> loginRecordList = loginRecordMapper.getListByUserId(userId);
        if(loginRecordList == null){
            ////logger.info("getTimeLiness-loginRecordList==null");
            return 0.0;
        }
        if(loginRecordList.size() == 0){
            ////logger.info("getTimeLiness-loginRecordList.size()==0");
            return 0.0;
        }
        LoginRecord loginRecord = loginRecordList.get(loginRecordList.size() - 1);
        long difference = nowTime - Long.parseLong(loginRecord.getLoginTime());
        if(difference <= 0){
            return 0.0;
        }else if(difference > 0 && difference <= 30 * 60 * 1000){
            return 50.0;
        }else if(difference < 60 * 60 * 1000){
            return 40.0;
        }else if(difference < 2 * 60 * 60 * 1000){
            return 30.0;
        }else if(difference < 3 * 60 * 60 * 1000){
            return 20.0;
        }else if(difference < 4 * 60 * 60 * 1000){
            return 10.0;
        }else {
            return 0.0;
        }
    }


    /**
     * 获取某用户的匹配度分数
     * @param userId 被推荐用户ID（当前向userId推荐用户）
     * @param id 待匹配用户
     * @return
     */
    public double getSuitability(long userId,long id){
        ////logger.info("getSuitability");
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        String labelString = userInfo.getLabel();
        String[] labels = labelString.split(",");
        String queryString = "";
        for (String string : labels){
            queryString += (string + " ");
        }

        double totalScore = 5.0 * labels.length;
        ////logger.info("totalScore : " + totalScore);

        //匹配用户标签的得分
        double score1 = 0;
        List searchUserResult = solrService.queryWithUserId(queryString, SolrFlag.USER, 0, 10, id);
        if(searchUserResult == null || searchUserResult.size() == 0){
            score1 = 0;
        }else {
            SolrDocument solrDocument = (SolrDocument)searchUserResult.get(0);
            double scoreOfUser = ((Float)solrDocument.getFieldValue("score")).doubleValue();
            score1 = scoreOfUser / totalScore * 25.0;

            if(score1 - 25.0 > 0){
                score1 = 25.0;
            }
        }

        //匹配用户相关分享贴的得分
        double score2 = 0;
        List<Article> articleList = articleMapper.getArticleList(id, ArticleFlag.SHARE);
        if(articleList == null || articleList.size() == 0){
            score2 = 0;
        }else {
            for (Article article : articleList){
                long articleId = article.getId();
                List searchArticleResult = solrService.queryWithTypeAndUserId(queryString, SolrFlag.ARTICLE, 0, 10, (byte) 1, articleId);
                if(searchArticleResult == null || searchArticleResult.size() == 0){
                    score2 += 0.0;
                }else {
                    SolrDocument solrDocument = (SolrDocument)searchArticleResult.get(0);
                    double scoreOfArticle = ((Float)solrDocument.getFieldValue("score")).doubleValue();
                    score2 += (scoreOfArticle / totalScore * 15);
                    if(score2 - 75.0 > 0){
                        score2 = 75.0;
                        break;
                    }
                }
            }
        }

        return score1 + score2;
    }


    /**
     * 获取某用户的权威性分数
     * @param userId
     * @return
     */
    public double getAuthoritative(long userId){
        ////logger.info("getAuthoritative");
        //分享贴得分
        long number = articleMapper.getArticleNumber(userId,ArticleFlag.SHARE);
        double score1 = number * 3.0;
        if(score1 - 15 > 0){
            score1 = 15.0;
        }

        //分享贴被回复&点赞得分
        double score2 = 0.0;
        List<Article> list = articleMapper.getArticleList(userId,ArticleFlag.SHARE);
        if(list == null || list.size() == 0){
            score2 = 0.0;
        }else {
            for (Article article : list){
                long commentNum = commentsOfArticleMapper.getCommentsNumber(article.getId());
                long approvalNum = approvalMapper.getApprovalNumber(article.getId(), CommonFlag.ARTICLE);
                long scanNum = scanRecordMapper.getScanNumber(article.getId());
                if(scanNum == 0){
                    continue;
                }
                double num = (commentNum + approvalNum) / (double)scanNum;
                if(num - 1 > 0){
                    score2 += 25;
                    break;
                }else {
                    score2 += (num * 5);
                    if(score2 - 25 > 0){
                        score2 = 25.0;
                        break;
                    }
                }
            }
        }

        //分享贴被收藏得分
        double score3 = 0.0;
        if(list == null || list.size() == 0){
            score3 = 0;
        }else {
            for (Article article : list){
                long num = favoriteMapper.getFavoriteNumber(article.getId(),CommonFlag.ARTICLE);
                score3 += num;
                if(score3 - 20 > 0){
                    score3 = 20.0;
                    break;
                }
            }
        }

        //回复他人求助帖得分
        double score4 = 0.0;
        List<CommentsOfArticle> commentsOfArticleList = commentsOfArticleMapper.getListByUserId(userId);
        if(commentsOfArticleList != null){
            score4 += commentsOfArticleList.size() * 0.5;
        }

        return score1 + score2 + score3 + score4;
    }
}
